package com.yunbiao.ybbusstopplate.utils;

import android.text.TextUtils;
import android.util.Log;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.convert.Converter;
import com.lzy.okrx2.adapter.ObservableResponse;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.Observer;
import io.reactivex.Scheduler;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class LeShanUtils {
    private static final String TAG = "LeShanUtils";
    private static final String TIME_URL = "http://221.10.114.137:5012/joffice/system/getAppInfoAppUser.do";
    public static void syncTime(Observer<List<Integer>> observer){
        OkGo.<TimeResponse>get(TIME_URL)
                .converter(new TimeResponseConverter(TAG,TIME_URL))
                .adapt(new ObservableResponse<>())
                .flatMap(new TimeCheckFunction())
                .map(timeResponse -> {
                    Log.d(TAG, "onNext: " + timeResponse);
                    List<TimeResponse.Result> results = timeResponse.getResult();
                    if(results != null && !results.isEmpty()){
                        TimeResponse.Result result = results.get(0);
                        long time = result.getTime();
                        String yyyyMMddHHmmss = TimeUtils.date2String(new Date(time * 1000), "yyyyMMddHHmmss");
                        int year = Integer.parseInt(yyyyMMddHHmmss.substring(0, 4));//年
                        int month = Integer.parseInt(yyyyMMddHHmmss.substring(4,6));//月
                        int day = Integer.parseInt(yyyyMMddHHmmss.substring(6,8));//日
                        int hours = Integer.parseInt(yyyyMMddHHmmss.substring(8,10));//日
                        int minutes = Integer.parseInt(yyyyMMddHHmmss.substring(10,12));//日
                        int seconds = Integer.parseInt(yyyyMMddHHmmss.substring(12));//日
                        return Arrays.asList(year, month, day, hours, minutes,seconds);
                    }
                    throw new Exception("获取服务器时间失败");
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .retry()
                .subscribe(observer);
    }

    public static class TimeResponse {

        private boolean success;
        private int totalCounts;
        private List<Result> result;

        public boolean isSuccess() {
            return success;
        }

        public void setSuccess(boolean success) {
            this.success = success;
        }

        public int getTotalCounts() {
            return totalCounts;
        }

        public void setTotalCounts(int totalCounts) {
            this.totalCounts = totalCounts;
        }

        public List<Result> getResult() {
            return result;
        }

        public void setResult(List<Result> result) {
            this.result = result;
        }

        public static class Result {
            private long id;
            private String app_version;
            private String download_address;
            private String app_package;
            private String enabled;
            private String cid;
            private String cname;
            private long time;

            public long getId() {
                return id;
            }

            public void setId(long id) {
                this.id = id;
            }

            public String getApp_version() {
                return app_version;
            }

            public void setApp_version(String app_version) {
                this.app_version = app_version;
            }

            public String getDownload_address() {
                return download_address;
            }

            public void setDownload_address(String download_address) {
                this.download_address = download_address;
            }

            public String getApp_package() {
                return app_package;
            }

            public void setApp_package(String app_package) {
                this.app_package = app_package;
            }

            public String getEnabled() {
                return enabled;
            }

            public void setEnabled(String enabled) {
                this.enabled = enabled;
            }

            public String getCid() {
                return cid;
            }

            public void setCid(String cid) {
                this.cid = cid;
            }

            public String getCname() {
                return cname;
            }

            public void setCname(String cname) {
                this.cname = cname;
            }

            public long getTime() {
                return time;
            }

            public void setTime(long time) {
                this.time = time;
            }
        }
    }
    public static class TimeResponseConverter implements Converter<TimeResponse> {
        private final String TAG;
        private final String URL;

        public TimeResponseConverter(String TAG, String URL) {
            this.TAG = "TimeResponseConverter";
            this.URL = URL;
        }

        //    private boolean test = true;
        @Override
        public TimeResponse convertResponse(Response response) throws Throwable {
            ResponseBody body = response.body();
            if (body == null) {
                throw new Exception("request failed");
            }

            String string = body.string();
//        if(test){
//            string = ResourceUtils.readAssets2String("test_hy1");
//        } else {
//            string = ResourceUtils.readAssets2String("test_hy2");
//        }
//        test = !test;

            d("请求响应：" + string);
            if(TextUtils.isEmpty(string)){
                throw new Exception("request empty");
            }

            TimeResponse timeResponse = GsonUtils.fromJson(string, TimeResponse.class);
            if(timeResponse == null){
                throw new Exception("format to PublicityResponse failed");
            }

            return timeResponse;
        }

        private void d(String log){
            LogUtils.d(TAG,TAG + ":" + log);
        }
    }

    public static class TimeCheckFunction implements Function<com.lzy.okgo.model.Response<TimeResponse>, ObservableSource<TimeResponse>> {
        private static final String TAG = "PublicityCheckFunction";

        @Override
        public ObservableSource<TimeResponse> apply(com.lzy.okgo.model.Response<TimeResponse> TimeResponseResponse) throws Exception {
            if (!TimeResponseResponse.isSuccessful()) {
                return Observable.error(new Exception("request failed"));
            }

            TimeResponse body = TimeResponseResponse.body();

            if(body.isSuccess()){
                //成功直接放行
            } else {
                return Observable.error(new Exception("get time failed"));
            }

            return Observable.just(body);
        }
    }

}
